//
//  CitySelectorViewController.swift
//  SoolyWeather
//
//  Created by SoolyChristina on 2017/3/9.
//  Copyright © 2017年 SoolyChristina. All rights reserved.
//

import UIKit
import CoreLocation

private let nomalCell = "nomalCell"
private let hotCityCell = "hotCityCell"
private let recentCell = "rencentCityCell"
private let currentCell = "currentCityCell"

class CitySelectorViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()
    var currLocation: CLLocation!
    var city = ""
    @IBAction func disItem(_ sender: UIBarButtonItem) {
        self.dismiss(animated: true, completion: nil)
    }
    
    
    
    /// 表格
    lazy var tableView: UITableView = UITableView(frame: self.view.frame, style: .plain)
    var cityDic: [String: [String]] = { () -> [String : [String]] in
        let path = Bundle.main.path(forResource: "cities.plist", ofType: nil)
        let dic = NSDictionary(contentsOfFile: path ?? "") as? [String: [String]]
        return dic ?? [:]
        }()
    lazy var titleArray: [String] = { () -> [String] in
       var array = [String]()
        for str in self.cityDic.keys {
            array.append(str)
        }
        // 标题排序
        array.sort()
//        array.insert("热门", at: 0)
//        array.insert("最近", at: 0)
        array.insert("当前", at: 0)
        return array
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestLocation()
        initLocation()
    }
    
    func initLocation() {
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
        locationManager.requestWhenInUseAuthorization()
        
    }
    
    func LonLatToCity() {
        
        let geocoder: CLGeocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(currLocation) { (placemark, error) -> Void in
            
            if error == nil {
                let array = placemark! as NSArray
                let mark = array.firstObject as! CLPlacemark
                let ci: String = (mark.addressDictionary! as NSDictionary).value(forKey: "City") as! String
                self.city = ci
                locCity = ci
                self.tableView.reloadData()
            } else {
                self.noticeError("定位失败", autoClear: true, autoClearTime: 2)
            }}}
    
    private func setupUI() {
        self.title = "选择城市"
        self.navigationController?.navigationBar.barTintColor = UIColor.white
        self.navigationController?.navigationBar.tintColor = UIColor.black
        self.navigationController?.navigationBar.titleTextAttributes = {[
            NSForegroundColorAttributeName: UIColor.black,
            NSFontAttributeName: UIFont.systemFont(ofSize: 18)
            ]}()
        
        // 设置tableView
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: nomalCell)
        tableView.register(RecentCitiesTableViewCell.self, forCellReuseIdentifier: recentCell)
        tableView.register(CurrentCityTableViewCell.self, forCellReuseIdentifier: currentCell)
        tableView.register(HotCityTableViewCell.self, forCellReuseIdentifier: hotCityCell)
        
        // 右边索引
        tableView.sectionIndexColor = UIColor.blue
        //tableView.sectionIndexTrackingBackgroundColor = UIColor.blue//white
        tableView.sectionIndexBackgroundColor = UIColor.clear
        self.view.addSubview(tableView)
    }
    
    deinit {
        print("我走了")
    }
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
            locationManager.requestLocation()
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location:CLLocation = locations[locations.count-1]
        currLocation = locations.last!
        //判断是否为空
        if location.horizontalAccuracy > 0 {
            LonLatToCity()
            //停止定位
            self.locationManager.stopUpdatingLocation()
        }
    }
    
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        //print("error:: \(error)")
    }
    
    func re() {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NewHomeReload"), object: nil)
    }

}

// MARK: tableView 代理方法、数据源方法
extension CitySelectorViewController: UITableViewDataSource, UITableViewDelegate {

    func numberOfSections(in tableView: UITableView) -> Int {
        return titleArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        } else {
            return cityDic[titleArray[section]]!.count
        }
    }
    
    // MARK: 创建cell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: nomalCell, for: indexPath)
            //let key = titleArray[indexPath.section]
            cell.textLabel?.text = "定位城市:" + city
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: nomalCell, for: indexPath)
            let key = titleArray[indexPath.section]
            cell.textLabel?.text = cityDic[key]![indexPath.row]
            return cell
        }
    }
    // MARK: 点击cell
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: false)
        if indexPath.section == 0 && indexPath.row == 0 {
            UserDefaults.standard.set(city, forKey: "cityKey")
            //let x = UserDefaults.standard.object(forKey: "cityKey") as! String
        } else {
            let cell = tableView.cellForRow(at: indexPath)
            //print("点击了 \(cell?.textLabel?.text ?? "")")
            let x = cell?.textLabel?.text ?? ""
            UserDefaults.standard.set(x, forKey: "cityKey")
        }
        self.dismiss(animated: true, completion: re)
    }
    
    // MARK: 右边索引
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return titleArray
    }
    
    // MARK: section头视图
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            let view = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: sectionMargin))
            let title = UILabel(frame: CGRect(x: 15, y: 5, width: ScreenWidth - 15, height: 28))
            title.text = "当前城市"
            title.font = UIFont.boldSystemFont(ofSize: 18)
            view.addSubview(title)
            view.backgroundColor = UIColor.groupTableViewBackground
            title.textColor = UIColor.lightGray
            
            return view
        } else {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: sectionMargin))
        let title = UILabel(frame: CGRect(x: 15, y: 5, width: ScreenWidth - 15, height: 28))
        var titleArr = titleArray
        title.text = titleArr[section]
        title.font = UIFont.boldSystemFont(ofSize: 18)
        view.addSubview(title)
            view.backgroundColor = UIColor.groupTableViewBackground
            title.textColor = UIColor.lightGray
        
        return view
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0
        } else {
            return 38
        }
    }
    
    // MARK: row高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 42
    }
}

